package com.dhcc.android.base.utils;

import android.app.Activity;
import android.content.Intent;
import android.view.View;

import com.dhcc.android.base.common.bean.File;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.gis.TouchLongToolCommen;
import com.example.collector.interoperation.CollectInteroperator;
import com.example.collector.interoperation.acticity.CollectActivity;
import com.example.collector.interoperation.acticity.ShearActivity;
import com.example.collector.interoperation.event.OnAreaBackListener;
import com.example.collector.interoperation.event.OnAreaSaveListener;
import com.example.collector.interoperation.event.OnCollectBackListener;
import com.example.collector.interoperation.event.OnCollectSaveListener;
import com.example.collector.interoperation.event.OnEditBackListener;
import com.example.collector.interoperation.event.OnEditSaveListener;
import com.example.collector.interoperation.event.OnShearBackListener;
import com.example.collector.interoperation.event.OnShearSaveListener;
import com.example.collector.tools.SaveGeometry;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import srs.GPS.GPSControl;
import srs.GPS.GPSConvert;
import srs.Geometry.Envelope;
import srs.Geometry.FormatConvert;
import srs.Geometry.IEnvelope;
import srs.Geometry.IGeometry;
import srs.Geometry.IPoint;
import srs.Geometry.Point;
import srs.Rendering.CommonRenderer;
import srs.Utility.sRSException;
import srs.tools.MapControl;

/**
 * 图斑地块处理包,为与一期项目区分，本工具类专为二期项目定制
 *
 * @author duanwg
 * @date 2016-1-16
 */
public class DKMapUtil {
    /**
     * 新增地块
     */
    public static final int ADD_DK = 1;
    /**
     * 拆分地块
     */
    public static final int CLIP_DK = 2;
    /**
     * 编辑地块
     */
    public static final int EDIT_DK = 3;

    private Activity activity;
    private MapControl demandMapControl;

    private static DBManagerUtil dbManagerUtil;

    private Map<String, String> yf_obj;

    public DKMapUtil(Activity activity) {
        this.activity = activity;
    }

    public DKMapUtil(Activity activity, DBManagerUtil dbManagerUtil, Map<String, String> yf_obj, MapControl dkSelectMapControl) {
        this.activity = activity;
        DKMapUtil.dbManagerUtil = dbManagerUtil;
        this.yf_obj = yf_obj;
        this.demandMapControl = dkSelectMapControl;
    }


    private Map<String, String> cfdk_obj;

    public void setCFDKObj(Map<String, String> cfdk_obj) {
        this.cfdk_obj = cfdk_obj;
    }

    /**
     * 新建地块
     *
     * @param file
     */
    public void addDK(final File file) {
        // add 杨宗仁 空间编辑，新建页面的跳转
        // CommenUtil.getMap()从当前mapControl获取map
        // srsGeometryType.Polygon是编辑多边形的类型参数，类型参数分为点、线、面
        CollectInteroperator.init(CommenUtil.getMap(), CommenUtil.getGeo(0)
                .GeometryType());
        CollectInteroperator.CollectEventManager
                .setOnCollectSaveListener(new SaveGeoListener(file));
        CollectInteroperator.CollectEventManager
                .setOnCollectBackListener(new BackGeoListener());
        Intent intent = new Intent(activity, CollectActivity.class);
        activity.startActivityForResult(intent, 2);
    }

    /**
     * 面积测算 add by duanwg
     *
     * @param file
     */
    public void calculateAcreage(final File file) {
        // CommenUtil.getMap()从当前mapControl获取map
        // srsGeometryType.Polygon是编辑多边形的类型参数，类型参数分为点、线、面
        System.out.println("!!:" + Constants.geometrys);
        CollectInteroperator.init(CommenUtil.getMap(), CommenUtil.getGeo(0)
                .GeometryType(), "几何计算");
        CollectInteroperator.CollectEventManager.setOnAreaSaveListener(new SaveGeoListener(file));
        CollectInteroperator.CollectEventManager.setOnAreaBackListener(new BackGeoListener());
        Intent intent = new Intent(activity, CollectActivity.class);
        intent.putExtra("obtainArea", true);
        activity.startActivityForResult(intent, 1);
    }


    /**
     * 删除地块
     */
    public boolean delDK(final File file, MapControl mapControl, String surveyDKIDPath) {
        boolean isSuccess = DKMapUtil.dbManagerUtil.deleteById(file.getTable(), "rowid", cfdk_obj.get("rowid"), surveyDKIDPath);
        if (isSuccess) {
            if (Constants.geometrys.size() > 0) {
                Constants.geometrys
                        .remove(TouchLongToolCommen.currentIndex);
                Constants.displayRenderBreaks
                        .remove(TouchLongToolCommen.currentIndex);
                Constants.displayLableNames.remove(TouchLongToolCommen.currentIndex);
            }

            //-----设置为分段渲染
            Constants.RENDERCBJ.AddBreak(0, "未填报", Constants.SYMBOLCBJ, null);
            Constants.RENDERCBJ.AddBreak(1, "已填报", Constants.SYMBOLCBJWC, null);
            try {
                Constants.COMMONLAYER.setRenderer(Constants.RENDERCBJ);
            } catch (sRSException e) {
                ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
                System.out.println("地块图层分段渲染有误！");
                e.printStackTrace();
            }
            //-----设置分段渲染完毕
            Constants.COMMONLAYER.setInitInfos("TableName",
                    Constants.geometrys, Constants.displayRenderBreaks,
                    srs.Geometry.srsGeometryType.Polygon,
                    Constants.displayLableNames, new Envelope(), null);
            /*((CommonRenderer) Constants.COMMONLAYER.getRenderer())
                    .setSymbol(Constants.SYMBOLCBJ);*/
            try {
                mapControl.getElementContainer().ClearElement();
            } catch (IOException e) {
                e.printStackTrace();
            }
//            mapControl.Refresh();
            CommenUtil.toast("删除成功！", activity);
        } else {
            CommenUtil.toast("删除失败！", activity);
        }

        return isSuccess;
    }

    /**
     * 剪切（拆分）地块
     *
     * @param file
     */
    public void clipDK(File file) {
        // add 杨宗仁 空间编辑,剪裁页面的跳转
        // CommenUtil.getMap()从当前mapControl获取map
        // new ArrayList<IGeometry>()剪切的几何对象的集合
        // 剪裁可保存为WKT格式

        // 获取要剪切的目标
        String wkt = cfdk_obj.get("GEO");
        List<IGeometry> geosCurrent = new ArrayList<IGeometry>();
        if (StringUtil.isNotEmpty(wkt)) {
            System.out.println("-----------" + wkt);
            try {
                IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                geosCurrent.add(geo);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        CollectInteroperator.init(CommenUtil.getMap(), geosCurrent);
        CollectInteroperator.CollectEventManager
                .setOnShearSaveListener(new SaveGeoListener(file));
        CollectInteroperator.CollectEventManager
                .setOnShearBackListener(new BackGeoListener());
        Intent intent = new Intent(activity, ShearActivity.class);
        activity.startActivityForResult(intent, 1);
    }

    /**
     * 编辑
     *
     * @param file
     */
    private void editDK(File file) {

        CollectInteroperator.init(CommenUtil.getMap(),
                CommenUtil.getGeo(TouchLongToolCommen.currentIndex));
        CollectInteroperator.CollectEventManager
                .setOnEditSaveListener(new SaveGeoListener(file));
        CollectInteroperator.CollectEventManager
                .setOnEditBackListener(new BackGeoListener());
        Intent intent = new Intent(activity, CollectActivity.class);
        activity.startActivity(intent);
    }

    /**
     * 空间编辑保存接口
     * <p/>
     * 杨宗仁
     *
     * @author Tudou
     */
    public class SaveGeoListener implements OnCollectSaveListener,
            OnShearSaveListener, OnEditSaveListener, OnAreaSaveListener {
        private File file;

        public SaveGeoListener(File file) {
            this.file = file;
        }

        @Override
        public boolean collectSave(EventObject event, double area) {// 新建保存
            String wkt = "";
            boolean result = true;
            System.out.println("#####新增面积：" + area);
            try {
                wkt = SaveGeometry.saveAsWKT();
                // 数据库中的GEO转换成wkt函数
                if (StringUtil.isNotEmpty(wkt)) {
                    IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                    Constants.geometrys.add(geo);

                    result = doWithGeo(file, wkt, ADD_DK, area, "", "GEO", "");
                }
            } catch (IOException e) {
                e.printStackTrace();
                result = false;
            }

            return result;
        }

        @Override
        public boolean shearSave(EventObject event, double[] areas) {// 剪切保存
            List<String> wktList = null;
            String YFBHU = "", GEO = "GEO", surveyDKIDPath = "";
            try {
                wktList = SaveGeometry.saveShearedGeosAsWKT();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            String oldid = cfdk_obj.get("YFDKBH");
            String frist = oldid.substring(0, oldid.indexOf("-") + 1);
            String filter = file.getPfeild() + "='" + YFBHU + "' and YFDKBH LIKE '" + frist + "%' ";
            List<String> dkbhlist = dbManagerUtil.getDKBHList(surveyDKIDPath, file.getTable(), filter);
            int big = getBigDKBH(dkbhlist, CLIP_DK);

            boolean isSuccess = DKMapUtil.dbManagerUtil.deleteById(file.getTable(), "rowid", cfdk_obj.get("rowid"), surveyDKIDPath);
            if (isSuccess) {
                if (Constants.geometrys.size() > 0) {
                    Constants.geometrys.remove(TouchLongToolCommen.currentIndex);
                    Constants.displayRenderBreaks.remove(TouchLongToolCommen.currentIndex);
                }
            }

            for (int i = 0; i < wktList.size(); i++) {
                String wkt = wktList.get(i);
                if (!StringUtil.isEmpty(wkt)) {
                    doWithGeoForShear(file, wkt, i + 1, big, areas[i], YFBHU, GEO, surveyDKIDPath);
                }
            }

            //-----设置为分段渲染
            Constants.RENDERCBJ.AddBreak(0, "未填报", Constants.SYMBOLCBJ, null);
            Constants.RENDERCBJ.AddBreak(1, "已填报", Constants.SYMBOLCBJWC, null);
            try {
                Constants.COMMONLAYER.setRenderer(Constants.RENDERCBJ);
            } catch (sRSException e) {
                ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
                System.out.println("地块图层分段渲染有误！");
                e.printStackTrace();
            }
            //-----设置分段渲染完毕

            Constants.COMMONLAYER.setInitInfos("TableName",
                    Constants.geometrys, Constants.displayRenderBreaks, srs.Geometry.srsGeometryType.Polygon,
                    Constants.displayLableNames, new Envelope(), null);
            /*((CommonRenderer) Constants.COMMONLAYER.getRenderer())
                    .setSymbol(Constants.SYMBOLCBJ);*/
            demandMapControl.Refresh();
            // 几何要素现实的图层

            return true;
        }

        @Override
        public boolean editSave(EventObject event) {// 编辑保存
            String wkt = "";
            String YFBHU = "", GEO = "GEO", surveyDKIDPath = "";
            try {
                wkt = SaveGeometry.saveAsWKT();
                IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                // Geometry geo=Geometry.CreateFromWkt(wkt);
                // 删除选中的编辑前的形状
                Constants.geometrys.remove(TouchLongToolCommen.currentIndex);
                Constants.geometrys.add(TouchLongToolCommen.currentIndex, geo);

            } catch (IOException e) {
                e.printStackTrace();
            }

            return doWithGeo(file, wkt, EDIT_DK, 0.0, YFBHU, GEO, surveyDKIDPath);
        }

        @Override
        /**面积采集*/
        public boolean areaSave(EventObject event) {

            return true;
        }
    }

    /**
     * 获取最大的编号
     */
    private int getBigDKBH(List<String> list, int type) {
        if (list.size() > 0) {

            int[] arr = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                String s = list.get(i);
                if (type == ADD_DK) {
                    if (s.contains("-")) {
                        String l = s.substring(0, s.indexOf("-"));
                        arr[i] = Integer.valueOf(l);
                    } else {
                        arr[i] = Integer.valueOf(s);
                    }
                } else if (type == CLIP_DK) {
                    String l = s.substring(s.indexOf("-") + 1);
                    arr[i] = Integer.valueOf(l);
                }
            }

            Arrays.sort(arr);

            return arr[list.size() - 1];
        } else {
            return 0;
        }
    }

    private String muToPf(double area) {
        area = area * 666.7;

        return String.valueOf(area);
    }


    private Boolean doWithGeo(File file, String wkt, int type, double area, String YFBHU, String surveyDKIDPath, String GEO) {
        Boolean isSuccess = false;
        try {

            //暂时不考虑修改，只考虑新增
            if (type == ADD_DK) {
                //获取到最大的编号
                String filter = file.getPfeild() + "='" + YFBHU + "' ";
                List<String> dkbhlist = dbManagerUtil.getDKBHList(surveyDKIDPath, file.getTable(), filter);
                int big = getBigDKBH(dkbhlist, ADD_DK);

                String dkbhu = DKMapUtil.dbManagerUtil.getLastDKBHU(file.getTable(), file.getPfeild(), YFBHU, surveyDKIDPath);
                String DKBHU = CommenUtil.getNewDKBHU(dkbhu);

                Map<String, String> saveMap = new HashMap<String, String>();
                saveMap.put("CUNMC", Constants.selects.get(0).get("CUNMC"));
                saveMap.put("CUNDM", Constants.selects.get(0).get("CUNDM"));
                saveMap.put("YFBH", yf_obj.get("YFBH"));
                saveMap.put(file.getPfeild(), YFBHU);
                saveMap.put("DKBHU", DKBHU);
                saveMap.put("YFDKBH", String.valueOf(big + 1));
                saveMap.put(GEO, wkt);
                saveMap.put("COMPLETE", "0");
                saveMap.put("TBMJ", muToPf(area));
                saveMap.put("TBLXMC", "");

                List<String> keyList = new ArrayList<String>();
                keyList.add("CUNMC");
                keyList.add("CUNDM");
                keyList.add("YFBH");
                keyList.add(file.getPfeild());
                keyList.add("DKBHU");
                keyList.add("YFDKBH");
                keyList.add(GEO);
                keyList.add("COMPLETE");
                keyList.add("TBMJ");
                keyList.add("TBLXMC");

                // 添加
                isSuccess = DKMapUtil.dbManagerUtil.add(saveMap,
                        keyList, file.getTable(), file.getPfeild(), surveyDKIDPath);// 只有一行数据
            }

            Constants.COMMONLAYER.setInitInfos("TableName",
                    Constants.geometrys, null, srs.Geometry.srsGeometryType.Polygon,
                    Constants.displayLableNames, new Envelope(), null);
            ((CommonRenderer) Constants.COMMONLAYER.getRenderer())
                    .setSymbol(Constants.SYMBOLCBJ);

            demandMapControl.Refresh();

            // 几何要素现实的图层
            if (!isSuccess) {
                CommenUtil.toast("保存失败！", activity);
            } else {
                Constants.data_refresh = true;
                CommenUtil.toast("保存成功！", activity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    /**
     * 切割数据库存储操作
     *
     * @param file
     * @param wkt
     * @return
     */
    private Boolean doWithGeoForShear(File file, String wkt, int i, int big, double area, String YFBHU, String GEO, String surveyDKIDPath) {
        Boolean isSuccess = false;
        try {
            String yfdkbh = getShearYFDKBH(cfdk_obj.get("YFDKBH"), big, i);
            String DKBHU = CommenUtil.getShearDKBHU(cfdk_obj.get("DKBHU"), big, i);

            Map<String, String> saveMap = new HashMap<String, String>();
            saveMap.put("CUNMC", Constants.selects.get(0).get("CUNMC"));
            saveMap.put("CUNDM", Constants.selects.get(0).get("CUNDM"));
            saveMap.put("YFBH", yf_obj.get("YFBH"));
            saveMap.put(file.getPfeild(), YFBHU);
            saveMap.put("DKBHU", DKBHU);
            saveMap.put("YFDKBH", yfdkbh);
            saveMap.put("YFDKBHBZ", yfdkbh);
            saveMap.put(GEO, wkt);
            saveMap.put("COMPLETE", "0");
            saveMap.put("TBLXMC", cfdk_obj.get("TBLXMC"));
            saveMap.put("TBMJ", String.valueOf(area));

            List<String> keyList = new ArrayList<String>();
            keyList.add("CUNMC");
            keyList.add("CUNDM");
            keyList.add("YFBH");
            keyList.add(file.getPfeild());
            keyList.add("DKBHU");
            keyList.add("YFDKBH");
            keyList.add("YFDKBHBZ");
            keyList.add(GEO);
            keyList.add("COMPLETE");
            keyList.add("TBLXMC");
            keyList.add("TBMJ");


            // 添加
            isSuccess = DKMapUtil.dbManagerUtil.add(saveMap, keyList, file.getTable(), file.getPfeild(),
                    surveyDKIDPath);// 只有一行数据


            Constants.geometrys.add(FormatConvert.WKTToPolygon(wkt));
            Constants.displayRenderBreaks.add(0.0);

            if (!isSuccess) {
                CommenUtil.toast("保存失败！", activity);
            } else {
                Constants.data_refresh = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    /**
     * 获取分割后地块编号
     */
    private String getShearYFDKBH(String oldid, int big, int i) {
        String nid = oldid;
        if (oldid.contains("-")) {
            String frist = oldid.substring(0, oldid.indexOf("-") + 1);
            int n = big + i;
            nid = frist + n;
        } else {
            nid = CommenUtil.getShearYFDKBH(oldid, i);
        }
        return nid;
    }


    /**
     * 空间编辑返回接口
     * <p/>
     * 杨宗仁
     *
     * @author Tudou
     */
    public class BackGeoListener implements OnCollectBackListener,
            OnShearBackListener, OnEditBackListener, OnAreaBackListener {

        @Override
        public boolean collectBack(EventObject event) {
            System.out.println("点击新建返回");
            return true;
        }

        @Override
        public boolean shearBack(EventObject event) {
            return true;
        }

        @Override
        public boolean editBack(EventObject event) {
            return true;
        }

        @Override
        public boolean areaBack(EventObject event) {
            return true;
        }
    }

    /**
     * 刷新tab 的地图数据
     *
     * @param childView
     */
    /**
     * @param childView
     * @param file
     */
    public void refreshCheckTab(View childView, File file, String YFBHU, String surveyDKIDPath) {

		/*
         * added by 李忠义 20150814 去掉前一个页面中在CommonLayer里的选中状态
		 */
        try {
            CommenUtil.getMap().getElementContainer().ClearElement();
        } catch (IOException e) {
            e.printStackTrace();
        }

		/* 获取到要显示的几何要素 */
        // 全局变量
        // 从数据库中获取数据
        List<String> strList = new ArrayList<String>();
        strList.add("GEO");
        if (StringUtil.isNotEmpty(file.getDklabelname())) {
            strList.add(file.getDklabelname());
        }
        System.out.println("-----strList:" + strList);
        final List<Map<String, String>> entityList = DKMapUtil.dbManagerUtil
                .getListData(file.getTable(), strList, file.getPfeild(),
                        YFBHU,
                        surveyDKIDPath);

		/*
         * added by lizhongyi 20150809 标签一定是要清空的
		 */
        Constants.displayLableNames.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        System.out.println("-----------" + wkt);
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }

                    }

					/*
					 * edited by lizhongyi 20150809 String LableID =
					 * map.get("DKNUMBER"); label未必都是DKNUMBER,应该是配置文件中取出来的
					 */
                    String LableID = "";
                    if (StringUtil.isNotEmpty(file.getDklabelname())) {
                        LableID = map.get(file.getDklabelname());
                    }

					/* edited by lizongyi 20150809 */
					/* if (isNotEmpty(LableID)) { */
                    if (LableID != null) {
                        System.out.println("-----------" + LableID);
						/* if (LableID != null) { */
						/*
						 * 就不会走到这里，因为前面geo里已经把isFirst设为false了 if (isFirst) {//
						 * 有数据后 第一次进来的时候 将清空 isFirst = false;
						 * Constants.displayLableNames.clear(); }
						 */
                        Constants.displayLableNames.add(LableID);
						/* } */

                    } else {
                        Constants.displayLableNames.add("");
                        System.out.println("未填写标注" + LableID);
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("~~~~:" + Constants.geometrys);
        // 几何要素现实的图层
        Constants.COMMONLAYER.setInitInfos("TableName"/* file.getTable() */,
                Constants.geometrys, null, srs.Geometry.srsGeometryType.Polygon,
                Constants.displayLableNames, new Envelope(), null);/* 不同页面更换数据与表名 */
        ((CommonRenderer) Constants.COMMONLAYER.getRenderer())
                .setSymbol(Constants.SYMBOLCBJ);
    }

    ;

    /**
     * 设置当前位置屏幕局中
     */
    public static void SetLocationCenter(MapControl mapControl) {
        IEnvelope mapEnv = mapControl.getActiveView().FocusMap().getExtent();
        GPSControl gpsControl = GPSControl.getInstance();
        double xy[] = GPSConvert.GEO2PROJECT(gpsControl.GPSLongitude,
                gpsControl.GPSLatitude, mapControl.getActiveView().FocusMap()
                        .getGeoProjectType());
        IPoint centerPoint = new Point(xy[0], xy[1]);
        double width = mapEnv.XMax() - mapEnv.XMin();
        double height = mapEnv.YMax() - mapEnv.YMin();
        IEnvelope envelope = new Envelope(centerPoint.X() - width / 2,
                centerPoint.Y() - height / 2, centerPoint.X() + width / 2,
                centerPoint.Y() + height / 2);
        mapControl.getActiveView().FocusMap().setExtent(envelope);
        mapControl.Refresh();
    }

}
